package org.hhh.basic.controller;

import org.hhh.basic.util.AjaxResult;
import org.hhh.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /**
     * 上传文件的接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            String filename = file.getOriginalFilename();//1.jpg
            String extName = filename.substring(filename.lastIndexOf(".") + 1);//jpg
            String uploadPath = FastDfsUtil.upload(file.getBytes(),extName );
            return AjaxResult.me().setResultObj(uploadPath);//把上传之后的相对路径设置给resultObj属性
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败");
        }
    }

    /**
     * 文件删除的接口
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String fileName  = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            FastDfsUtil.delete(groupName, fileName);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败");
        }

    }
}

